package com.xm.adv.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.viewpager.widget.PagerAdapter;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qilinkeji.daemon.QiLinDaemon;
import com.xm.adv.Ctr.DrawCtr;
import com.xm.adv.Ctr.OpenCloseCtr;
import com.xm.adv.DifferentDislay;
import com.xm.adv.R;
import com.xm.adv.view.dialog.SetDialog;
import com.xm.adv.view.dialog.UsbDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xinya.com.baselibrary.baseactivity.ZjbBaseActivity;
import xinya.com.baselibrary.bean.program.SceneBean;
import xinya.com.baselibrary.constant.Constant;
import xinya.com.baselibrary.eventbus.EventBusMsg;
import xinya.com.baselibrary.router.RouterUrl;
import xinya.com.baselibrary.service.MyService;
import xinya.com.baselibrary.utils.BackHandlerHelper;
import xinya.com.baselibrary.utils.LogUtil;
import xinya.com.baselibrary.utils.ScreenUtils;
import xinya.com.baselibrary.utils.greenDao.MyOpenHelper;
import xinya.com.db.DaoMaster;
import xinya.com.db.SceneBeanDao;

@Route(path = RouterUrl.Main.main_home)
public class MainActivity extends ZjbBaseActivity {


    @BindView(R.id.textActive)
    TextView textActive;
    @BindView(R.id.viewContent)
    RelativeLayout viewContent;
    @BindView(R.id.viewDraw01)
    RelativeLayout viewDraw01;
    @BindView(R.id.viewDraw02)
    RelativeLayout viewDraw02;
    //    @BindView(R.id.viewPager)
//    ViewPager viewPager;
    //    @BindView(R.id.recyclerView)
    //    @BindView(R.id.viewDraw)
////    RelativeLayout viewDraw;
    private SetDialog setDialog;
    private List<VideoView> videoViewList01;
    private ServiceConnection mconn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mbind = (MyService.MyBind) iBinder;
            mbind.getSetting();
            mbind.getList();
            for (int i = 0; i < listDb.size(); i++) {
                if (listDb.get(i).getDownloadComplete()) {
                    if (listDb.get(i).getScreen01() == 1) {
                        list01.add(listDb.get(i));
                    }
                    if (listDb.get(i).getScreen02() == 1) {
                        list02.add(listDb.get(i));
                    }
                } else {
                    mbind.startDownLoad(listDb.get(i));
                }
            }
//            pagerAdapter.notifyDataSetChanged();
            if (list01.size() > 0) {
                setDealy(0);
            }
            if (list02.size() > 0) {
                showDisplay();

            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    private void showDisplay() {
        if (mPresentation == null) {
            DisplayManager mDisplayManager;//屏幕管理类

            Display[] displays;//屏幕数组

            mDisplayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);

            displays = mDisplayManager.getDisplays();

            Log.e("MainActivity--onCreate", "" + displays.length);
            if (displays.length > 1) {
                //displays[1]是副屏
                mPresentation = new DifferentDislay(this, displays[1]);

                mPresentation.getWindow().setType(

                        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                mPresentation.show();
                mPresentation.setData(list02);
            }
        } else {
            mPresentation.show();
        }
    }

    private MyService.MyBind mbind;
    private boolean fromUsb;
    private UsbDialog usbDialog;
    private MyOpenHelper devOpenHelper;
    private DaoMaster daoMaster;
    private List<SceneBean> list01 = new ArrayList<>();
    private List<SceneBean> list02 = new ArrayList<>();
    private List<SceneBean> listDb;
    private List<VideoView> videoViewList02;
    private DifferentDislay mPresentation;
    //    private SamplePagerAdapter pagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setShouldReceiveEvent(true);
        ButterKnife.bind(this);
        QiLinDaemon.getInstance().startDaemon(this);
        init();
    }

    @Override
    protected void initSP() {
        devOpenHelper = new MyOpenHelper(getApplicationContext(), Constant.DB_NAME, null);
        daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        listDb = daoMaster.newSession().getSceneBeanDao().queryBuilder().list();
        if (listDb == null) {
            listDb = new ArrayList<>();
        }
        OpenCloseCtr.init(mContext);
    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        fromUsb = intent.getBooleanExtra(Constant.IntentKey.USB_FROM, false);
        showUsbDialog();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        fromUsb = intent.getBooleanExtra(Constant.IntentKey.USB_FROM, false);
        showUsbDialog();
    }

    @Override
    protected void initViews() {
        LogUtil.LogShitou("MainActivity--initViews", "" + ScreenUtils.getScreenWidth(mContext));
        LogUtil.LogShitou("MainActivity--initViews", "" + ScreenUtils.getScreenHeight(mContext));
//        pagerAdapter = new SamplePagerAdapter(this);
//        viewPager.setAdapter(pagerAdapter);


    }

    /**
     * usb
     */
    private void showUsbDialog() {
        if (fromUsb) {
            if (usbDialog != null) {
                usbDialog.dismiss();
                usbDialog = null;
            }
            usbDialog = new UsbDialog(mContext);
            usbDialog.show();
        }
    }

    @Override
    protected void initRecyclerview() {
    }

    @Override
    protected void initListener() {
    }

    int positionX = 0;
    int time = 15000;

    //延时翻页
    private void setDealy(int position) {
        positionX = position;
        if (runnable != null) {
            textActive.removeCallbacks(runnable);
        }
        add();
        runnable = () -> {
            if (list01.size() > 1) {
                if (viewDraw01.getVisibility() == View.VISIBLE) {
                    for (int i = 0; i < videoViewList02.size(); i++) {
                        videoViewList02.get(i).start();
                    }
                    viewDraw01.setVisibility(View.INVISIBLE);
                    viewDraw02.setVisibility(View.VISIBLE);
                    if (list01.size() > 1) {
                        LogUtil.LogShitou("MainActivity--setDealy", "1111");
                        int index = positionX;
                        index++;
                        if (index == list01.size()) {
                            index = 0;
                        }
                        videoViewList01 = DrawCtr.draw(MainActivity.this, viewDraw01, list01.get(index), 1, 0);
                    }
                } else {
                    for (int i = 0; i < videoViewList01.size(); i++) {
                        videoViewList01.get(i).start();
                    }
                    viewDraw01.setVisibility(View.VISIBLE);
                    viewDraw02.setVisibility(View.INVISIBLE);
                    if (list01.size() > 1) {
                        LogUtil.LogShitou("MainActivity--setDealy", "2222");
                        int index = positionX;
                        index++;
                        if (index == list01.size()) {
                            index = 0;
                        }
                        videoViewList02 = DrawCtr.draw(MainActivity.this, viewDraw02, list01.get(index), 1, 0);
                    }
                }
                SceneBean sceneBean = list01.get(positionX);
                String duration = sceneBean.getDuration();
                if (!TextUtils.isEmpty(duration)) {
                    time = Integer.parseInt(duration);
                }
                positionX++;
                if (positionX == list01.size()) {
                    positionX = 0;
                }
            }
            textActive.postDelayed(runnable, time);
        };
        textActive.postDelayed(runnable, time);
    }

    private void add() {
        viewDraw01.setVisibility(View.VISIBLE);
        viewDraw02.setVisibility(View.INVISIBLE);
        LogUtil.LogShitou("MainActivity--add", "" + list01.get(positionX).getId());
        videoViewList01 = DrawCtr.draw(MainActivity.this, viewDraw01, list01.get(positionX), 1, 0);
        SceneBean sceneBean01 = list01.get(positionX);
        String duration = sceneBean01.getDuration();
        if (!TextUtils.isEmpty(duration)) {
            time = Integer.parseInt(duration);
        }
        positionX++;
        if (positionX == list01.size()) {
            positionX = 0;
        }
        videoViewList02 = DrawCtr.draw(MainActivity.this, viewDraw02, list01.get(positionX), 1, 0);
    }


    @Override
    protected void initData() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            if (setDialog != null) {
                setDialog.dismiss();
                setDialog = null;
            }
            setDialog = new SetDialog(mContext);
            setDialog.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 双击退出应用
     */
    private long currentTime = 0;


    @Override
    public void onBackPressed() {
        if (!BackHandlerHelper.handleBackPress(this)) {
            if (System.currentTimeMillis() - currentTime > 1000) {
                Toast toast = Toast.makeText(this, "双击退出应用", Toast.LENGTH_SHORT);
                toast.show();
                currentTime = System.currentTimeMillis();
            } else {
//                QiLinDaemon.getInstance().stopDaemon();
//                MyApplication.getInstance().exit();
//                Process.killProcess(Process.myPid());
//                System.exit(0);
                finish();
            }
        }
    }

    @OnClick(R.id.textActive)
    public void onViewClicked() {
        if (setDialog != null) {
            setDialog.dismiss();
            setDialog = null;
        }
        setDialog = new SetDialog(mContext);
        setDialog.show();
    }

    @Override
    public void onStart() {
        super.onStart();
        Intent intent = new Intent();
        intent.setClass(this, MyService.class);
        bindService(intent, mconn, Context.BIND_AUTO_CREATE);
        startService(intent);
//        String screenRoate01 = ACacheX.getAsString(mContext, Constant.AcacheKey.setInfo, Constant.AcacheValue.screenRoate01);
//        if (TextUtils.isEmpty(screenRoate01)) {
//            viewContent.setRotation(0);
//        } else if (TextUtils.equals(screenRoate01, "0")) {
//            viewContent.setRotation(0);
//        } else if (TextUtils.equals(screenRoate01, "90")) {
//            viewContent.setRotation(90);
//        } else if (TextUtils.equals(screenRoate01, "180")) {
//            viewContent.setRotation(180);
//        } else if (TextUtils.equals(screenRoate01, "270")) {
//            viewContent.setRotation(270);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mconn);
        Constant.MainActivityAlive = 0;
    }

    /**
     * des： 图片adapter
     * author： ZhangJieBo
     * date： 2017/7/6 0006 下午 2:18
     */
    class SamplePagerAdapter extends PagerAdapter {

        private Context mContext;

        public SamplePagerAdapter(Context context) {
            this.mContext = context;
        }

        @Override
        public int getCount() {
            return list01.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, final int position) {
            LinearLayout linearLayout = new LinearLayout(mContext);
            linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            linearLayout.setBackgroundColor(Color.parseColor(list01.get(position).getBackground()));
            RelativeLayout relativeLayout = new RelativeLayout(mContext);
            relativeLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            linearLayout.addView(relativeLayout);
            List<VideoView> draw = DrawCtr.draw(MainActivity.this, relativeLayout, list01.get(position), 1, 0);
            container.addView(linearLayout, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            return linearLayout;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }

    private Runnable runnable;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventReceiver(EventBusMsg eventBusMsg) {
        switch (eventBusMsg.key) {
            case Constant.EventKey.closeUsb:
                if (usbDialog != null) {
                    usbDialog.dismiss();
                    usbDialog = null;
                }
                break;
            case Constant.EventKey.NEW_ADV:
                LogUtil.LogShitou("MainActivity--onEventReceiver", "收到新广告");
                SceneBean scene = (SceneBean) eventBusMsg.value;
                boolean isExit = false;
                for (int i = 0; i < list01.size(); i++) {
                    if (scene.getScreen01() == 1 && list01.get(i).getId() == scene.getId()) {
                        isExit = true;
                        break;
                    }
                }
                for (int i = 0; i < list02.size(); i++) {
                    if (scene.getScreen02() == 1 && list02.get(i).getId() == scene.getId()) {
                        isExit = true;
                        break;
                    }
                }
                if (!isExit) {
                    if (scene.getScreen01() == 1) {
                        list01.add(scene);
                    }
                    if (list01.size() == 1) {
                        setDealy(0);
                    }
//                    if (scene.getScreen02() == 1) {
////                        mPresentation.show();
//                        LogUtil.LogShitou("MainActivity--onEventReceiver", "屏2添加节目");
//                        mPresentation.addProgram(scene);
//                    }
                    if (list02.size() == 0) {
                        list02.add(scene);
//                        mPresentation.show();
                        LogUtil.LogShitou("MainActivity--onEventReceiver", "屏2添加节目");
                        showDisplay();
                    } else {
                        LogUtil.LogShitou("MainActivity--onEventReceiver", "屏2添加节目");
                        mPresentation.addProgram(scene);
                    }
                }
                break;
            case Constant.EventKey.SCROLL:

                break;
            case Constant.EventKey.clearAll:
                SceneBeanDao sceneBeanDao = daoMaster.newSession().getSceneBeanDao();
                sceneBeanDao.deleteAll();
                list01.clear();
                if (videoViewList01 != null) {
                    for (int i = 0; i < videoViewList01.size(); i++) {
                        videoViewList01.get(i).stopPlayback();
                    }
                }
                if (videoViewList02 != null) {
                    for (int i = 0; i < videoViewList02.size(); i++) {
                        videoViewList02.get(i).stopPlayback();
                    }
                }
                viewDraw01.setVisibility(View.INVISIBLE);
                viewDraw02.setVisibility(View.INVISIBLE);

                list02.clear();
                if (mPresentation != null) {
                    mPresentation.dismiss();
                }
                break;
            default:
                break;
        }
    }

}
